﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RPGXEngine
{
    public class Command_Variable : ICommand
    {
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private string _name = String.Empty;

        public ICommand ArrayOrdinal
        {
            get { return _arrayOrdinal; }
            set { _arrayOrdinal = value; }
        }
        private ICommand _arrayOrdinal = null;

        #region ICommand Members

        public bool IsReturn { get { return false; } }
        public bool IsIf { get { return false; } }

        public List<ICommand> ChildrenCommands
        {
            get
            {
                return this._childrenCommands;
            }
        }
        private List<ICommand> _childrenCommands = new List<ICommand>();

        public IVariableType Execute(ScriptManager sm, FunctionScope scope)
        {
            IVariableType value = null;

            if (this.ChildrenCommands.Count > 0)
            {
                // these only should be functions
                // and we should only have one
                value = this.ChildrenCommands[0].Execute(sm, scope); // maybe these functions need to be a new type of command, Command_ClassFunction which automatically adds the calling variable as the first argument...?
            }
            else
            {
                foreach (var a in scope.Arguments)
                {
                    if (a.Name.ToLower() == this.Name.ToLower())
                    {
                        value = a;
                        break;
                    }
                }

                foreach (var a in scope.Variables)
                {
                    if (a.Name.ToLower() == this.Name.ToLower())
                    {
                        value = a;
                        break;
                    }
                }

                if (value.Type == DataType.Array && value is ArrayVariableType && this.ArrayOrdinal != null)
                {
                    ((ArrayVariableType)value).ArrayOrdinal = this.ArrayOrdinal.Execute(sm, scope);
                }
            }

            return value;
        }

        #endregion
    }
}
